package com.qianxx.base;

import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.qianxx.draw.R;
import com.qianxx.base.widget.RefreshLayout;
import com.qianxx.base.widget.RefreshLayout.OnLoadListener;

/**
 * 包含"上拉加载下拉刷新"的Activity
 */
public class BaseRefreshAty extends BaseAty implements OnRefreshListener,
		OnLoadListener {

	protected final static String Refresh = "Refresh"; // 下拉刷新，使用该请求码
	protected final static String Load = "Load"; // 上拉加载，使用该请求码

	private RefreshLayout mRefreshLayout;
	protected ListView mRefreshListView;

	// 初始化相应的控件
	protected void initRefreshLayout() {
		// 布局中需要包含 lay_refresh
		mRefreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
		// 刷新图标修改为蓝色
		mRefreshLayout.setColorSchemeResources(R.color.base_orange);

		mRefreshListView = (ListView) findViewById(R.id.refreshList);
		// 11-11 为解决bug，将添加footerView的操作从RefreshLayout移到BaseRefreshAty中
		mRefreshLayout.initLayFooter(mRefreshListView, this);
		// 设置监听
		mRefreshLayout.setOnRefreshListener(this);
		mRefreshLayout.setOnLoadListener(this);
	}

	/**
	 * 刚进入界面时，可以调用该方法，触发类似"下拉加载"的效果
	 */
	protected void startRefresh() {
		final View root = getRootView();
		root.getViewTreeObserver().addOnGlobalLayoutListener(
				new ViewTreeObserver.OnGlobalLayoutListener() {
					@Override
					public void onGlobalLayout() {
						root.getViewTreeObserver()
								.removeGlobalOnLayoutListener(this);
						mRefreshLayout.setRefreshing(true);
						onRefresh();
					}
				});
	}

	/**
	 * 如果要为mRefreshLayout添加HeaderView请使用此方法；
	 * 
	 * 为了确保RefreshLayout中的setTvDisplay方法，判断数据个数正常。
	 */
	protected void addHeaderView(View headerView, BaseAdapter myAdapter) {
		mRefreshListView.addHeaderView(headerView);
		mRefreshLayout.setMyAdapter(myAdapter); // 为确保数据个数判断正确
	}

	/**
	 * 下拉刷新
	 */
	@Override
	public void onRefresh() {
		// 请使用无loading指示的请求方法
		// requestDataWithoutLoading(requestTag, url, method, bean, params);
		mRefreshLayout.postDelayed(new Runnable() {

			@Override
			public void run() {
				// 更新完后调用该方法结束刷新
				onRefreshComplete();
			}
		}, 1000);
	}

	protected void onRefreshComplete() {
		mRefreshLayout.setTvDisplay(); // 判断adapter中的数据个数是否为0，如果为0则不显示tvLoadMore
		mRefreshLayout.setRefreshing(false);
	}

	/**
	 * 上拉加载
	 */
	@Override
	public void onLoad() {
		// 请使用无loading指示的请求方法
		// requestDataWithoutLoading(requestTag, url, method, bean, params);
		mRefreshLayout.postDelayed(new Runnable() {
			@Override
			public void run() {
				// 加载完后调用该方法
				onLoadComplete();
			}
		}, 1000);
	}

	protected void onLoadComplete() {
		mRefreshLayout.setLoading(false);
	}

	// 没有更多数据
	protected void hasNoMoreData(boolean hasNoMoreData) {
		mRefreshLayout.setTvLoadMore(hasNoMoreData);
	}

	// 去掉头部的线条
	protected void delDivider() {
		mRefreshListView.setDivider(null);
	}
}
